package com.xiecong.exception;

import com.xiecong.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("出现异常", e);
        return Result.error("服务器异常!");
    }


    @ExceptionHandler
    public Result handleException(DuplicateKeyException e) {
        String message = e.getCause().getMessage();
        log.error("出现异常", e);
        String[] msg = message.split(" ");
        return Result.error("【" + msg[2] + "】重复了");
    }

    /**
     * 处理运行时抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result handleException(RuntimeException e) {
        log.error("出现异常", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        //检验没通过的字段
        List<ObjectError> allErrors = e.getAllErrors();
        StringJoiner sj = null;
        if (!CollectionUtils.isEmpty(allErrors)) {
            sj = new StringJoiner(",");
            for (ObjectError error : allErrors) {
                //校验不通过时的提示信息
                String info = error.getDefaultMessage();
                sj.add(info);
            }
        }
        return Result.error(sj.toString());
        /*String errorInfo = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";"));
        return Result.error(errorInfo);*/

    }
}
